package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author：徐志荣
 * @Date：2023/5/30 下午 4:01
 */

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.setCharacterEncoding("utf8");
      resp.setContentType("text/html;charset=utf8");
        //1.读取参数中的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null  || "".equals(username)|| password == null || "".equals(password)){
            //登录失败
            String html = "<h3>登录失败,缺少 username或者password字段</h3>";
            resp.getWriter().write(html);
            return;
        }
        //读取数据
        UserDao userDao = new UserDao();
        User user = userDao.selectByUsername(username);
        if(user == null){
            String html = "<h3>登录失败,用户名或者密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())){
            String html = "<h3>登录失败,用户名或者密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
        //3.登陆成功,创建会话,使用该会话保存用户信息
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        HttpSession session = req.getSession(false);
        if(session == null){
            //未登录,返回一个空的user对象
            User user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        User user = (User)session.getAttribute("user");
        if(user == null){
            user = new User();
            String respJson = objectMapper.writeValueAsString(user);
            resp.getWriter().write(respJson);
            return;
        }
        //确实成功取出了 user对象,就直接返回即可
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
